package com.googlecode.recycled.drools;

import com.googlecode.recycled.lang.assertions.Assert;
import org.drools.event.rule.DefaultWorkingMemoryEventListener;
import org.drools.event.rule.ObjectInsertedEvent;
import org.drools.event.rule.ObjectRetractedEvent;

import javax.annotation.Nullable;

public class FactHandlerListener extends DefaultWorkingMemoryEventListener implements FactHandlerHistory {

    protected final FactHandler factHandler;

    public FactHandlerListener() {
        this.factHandler = new MemoryStoreFactHandler();
    }

    public FactHandlerListener(FactHandler factHandler) {
        this.factHandler = Assert.notNull(factHandler);
    }

    @Override
    public void objectInserted(@Nullable ObjectInsertedEvent event) {
        factHandler.insert(event.getObject());
    }

    @Override
    public void objectRetracted(@Nullable ObjectRetractedEvent event) {
        factHandler.retract(event.getOldObject());
    }

    @Override
    public Iterable<Object> getFactsHistory() {
        if (!(factHandler instanceof FactHandlerHistory)) {
            throw new UnsupportedOperationException();
        }
        return ((FactHandlerHistory) factHandler).getFactsHistory();
    }

}
